package jsyf.oa.service.apply;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import net.sourceforge.pinyin4j.PinyinHelper;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import jsyf.com.util.DateUtils;
import jsyf.oa.dao.apply.MoneyAuditDao;
import jsyf.oa.dao.apply.MoneyCopierDao;
import jsyf.oa.dao.apply.MoneyMainDao;
import jsyf.oa.dao.apply.MoneyPayAuditDao;
import jsyf.oa.dao.apply.MoneyPayeeDao;
import jsyf.oa.dao.apply.MoneyPayerDao;
import jsyf.oa.dao.attach.AttachModuleDao;
import jsyf.oa.dao.system.AuditDao;
import jsyf.oa.dao.system.AuditHistoryDao;
import jsyf.oa.dao.system.CheckDao;
import jsyf.oa.dao.system.CompanyDao;
import jsyf.oa.dao.system.MessageDao;
import jsyf.oa.dao.system.MessageReceiverDao;
import jsyf.oa.dao.system.RightOpDao;
import jsyf.oa.dao.system.User2RightOpDao;
import jsyf.oa.dao.system.UserDao;
import jsyf.oa.dao.wechat.service_company.TokenDao;
import jsyf.oa.entity.apply.MoneyAuditEntity;
import jsyf.oa.entity.apply.MoneyCopierEntity;
import jsyf.oa.entity.apply.MoneyEntity;
import jsyf.oa.entity.apply.MoneyMainEntity;
import jsyf.oa.entity.apply.MoneyPayAuditEntity;
import jsyf.oa.entity.apply.MoneyPayeeEntity;
import jsyf.oa.entity.attach.AttachModuleEntity;
import jsyf.oa.entity.attach.AttachmentEntity;
import jsyf.oa.entity.system.AuditEntity;
import jsyf.oa.entity.system.AuditHistoryEntity;
import jsyf.oa.entity.system.MessageEntity;
import jsyf.oa.entity.system.MessageReceiverEntity;
import jsyf.oa.entity.system.UserEntity;
import jsyf.oa.facade.apply.MoneyFacade;

import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.*;
import static jsyf.oa.dao.wechat.service_company.TokenDao.PushTemplate.MONEY_AUDIT_NOTIFY;

/**
 * @author Lenovo
 * @date 2017/12/1
 */
@SuppressWarnings("all")
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class MoneyService implements MoneyFacade {

    @Autowired
    private MoneyMainDao moneyMainDao;

    @Autowired
    private CheckDao checkDao;

    @Autowired
    private MoneyPayeeDao moneyPayeeDao;

    @Autowired
    private MoneyCopierDao moneyCopierDao;

    @Autowired
    private MoneyAuditDao moneyAuditDao;

    @Autowired
    private AttachModuleDao attachModuleDao;

    @Autowired
    private MoneyPayAuditDao moneyPayAuditDao;

    @Autowired
    private MoneyPayerDao moneyPayerDao;

    @Autowired
    private RightOpDao rightOpDao;

    @Autowired
    private User2RightOpDao user2RightOpDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private AuditDao auditDao;

    @Autowired
    private CompanyDao companyDao;

    @Autowired
    private AuditHistoryDao auditHistoryDao;

    @Autowired
    private MessageDao messageDao;

    @Autowired
    private MessageReceiverDao messageReceiverDao;

    /**
     * 企业号服务
     */
    @Autowired
    private TokenDao tokenDao;

    /*//回款
    @Override
    public JSONObject saveRefund(String jsonData) {
        MoneyEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), MoneyEntity.class);
        List<JSONObject> jsonObjectList = new ArrayList<>();
        MoneyMainEntity newMoneyMainEntity = entity.getMain();
        String id = newMoneyMainEntity.getId();
        auditDao.removeByCondition(" AND MAIN_ID=? AND MODULE_NAME='moneyRefund'", new String[]{id});
        MoneyMainEntity oldMoneyMainEntity = moneyMainDao.getEntityById(id);

        oldMoneyMainEntity.setRefundFlag(newMoneyMainEntity.getRefundFlag());
        oldMoneyMainEntity.setHaveRefund(newMoneyMainEntity.getHaveRefund());
        oldMoneyMainEntity.setEstimatedReturnDate(newMoneyMainEntity.getEstimatedReturnDate());
        oldMoneyMainEntity.setEstimatedReturnMoney(newMoneyMainEntity.getEstimatedReturnMoney());
        oldMoneyMainEntity.setActualReturnDate(newMoneyMainEntity.getActualReturnDate());
        oldMoneyMainEntity.setActualReturnMoney(newMoneyMainEntity.getActualReturnMoney());
        oldMoneyMainEntity.setHaveReturnClear(newMoneyMainEntity.getHaveReturnClear());
        oldMoneyMainEntity.setReturnRemark(newMoneyMainEntity.getReturnRemark());

        List<AuditEntity> auditEntityList = entity.getAuditList();
        if (null != auditEntityList && auditEntityList.size() > 0) {
            for (int i = 0; i < auditEntityList.size(); i++) {
                AuditEntity auditEntity = auditEntityList.get(i);
                String auditorNameAndRoleName = auditEntity.getAuditorName();
                //String refundFlag = oldMoneyMainEntity.getRefundFlag();
                if (auditorNameAndRoleName.indexOf("-") > 0) {
                    String[] nameList = auditorNameAndRoleName.split("-");
                    String auditId = auditEntity.getAuditorId();
                    String auditName = nameList[1];
                    String auditRoleName = nameList[0];
                    if (i == 0) {
                        oldMoneyMainEntity.setCurrentAuditorId(auditId);
                        oldMoneyMainEntity.setCurrentAuditorName(auditName);
                    }
                    auditEntity.setAuditorId(auditId);
                    auditEntity.setRoleName(auditRoleName);
                    auditEntity.setAuditorName(auditName);
                }
                //-1 跟踪人第一审核草稿（上级） 0审核中 1通过 2驳回

                if (i == 0) {
                    auditEntity.setAuditFlag(0);


                    //企业号:给第一审核人发送消息
                    JSONObject msgObject = new JSONObject();
                    msgObject.put("userIds", auditEntity.getAuditorId());
                    msgObject.put("content", String.format(REFUND_AUDIT,
                            auditEntity.getAuditorName(),
                            oldMoneyMainEntity.getReturnPayeeName(),
                            oldMoneyMainEntity.getReturnPayeeName(),
                            DateUtils.parse(moneyMainDao.getCurrentTime(), "yyyy-MM-dd HH:mm")
                    ));
                    tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

                    messageReceiverRead(oldMoneyMainEntity.getId(), 0);
                    messageReceiverRead(oldMoneyMainEntity.getId(), 2);

                    //保存消息到消息表t_sys_message
                    MessageEntity messageEntity = new MessageEntity();
                    messageEntity.setCreateUserId(oldMoneyMainEntity.getReturnPayeeId());
                    messageEntity.setCreateTime(messageDao.getCurrentTime());
                    messageEntity.setContent(String.format(REFUND_AUDIT,
                            auditEntity.getAuditorName(),
                            oldMoneyMainEntity.getReturnPayeeName(),
                            oldMoneyMainEntity.getReturnPayeeName(),
                            DateUtils.parse(moneyMainDao.getCurrentTime(), "yyyy-MM-dd HH:mm")
                    ));
                    messageEntity.setMessageType(1);//1审核 0通知
                    messageEntity.setMainId(oldMoneyMainEntity.getId());
                    messageEntity.setDelFlag(0);
                    messageEntity.setOpenUrl("/page/apply/money/genzong_detail.html?id=" + oldMoneyMainEntity.getId() + "&pageType=applyAudit&openType=dialog");
                    messageEntity.setOpenTitle(String.format(REFUND_AUDIT_MESSAGE, oldMoneyMainEntity.getReturnPayeeName()));
                    messageDao.add(messageEntity);

                    //保存第一审核人信息到消息收件人表t_sys_message_receiver
                    MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
                    messageReceiverEntity.setMessageId(messageEntity.getId());
                    messageReceiverEntity.setUserId(oldMoneyMainEntity.getCurrentAuditorId());
                    messageReceiverEntity.setUserType(0);
                    messageReceiverEntity.setReadFlag(0);
                    messageReceiverDao.add(messageReceiverEntity);

                    //发消息
                    jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));


                } else {
                    auditEntity.setAuditFlag(-1);
                }
                auditEntity.setAuditAdvise(null);
                auditEntity.setAuditTime(null);
                auditEntity.setMainId(id);
                auditEntity.setModuleName("moneyRefund");
                auditEntity.setAuditSort(i);
                auditDao.add(auditEntity);
            }
        }

        moneyMainDao.update(oldMoneyMainEntity);

        JSONObject result = new JSONObject();
        result.put("flag", true);
        result.put("message", jsonObjectList);
        return result;
    }*/
    @Override
    public JSONObject saveRefund(String jsonData) {
        return null;
    }

    @Override
    public JSONObject save(String jsonData) {
        JSONObject result = new JSONObject();
        List<JSONObject> jsonObjectList = new ArrayList<>();
        MoneyEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), MoneyEntity.class);

        //第一步，保存主表信息
        MoneyMainEntity moneyMainEntity = entity.getMain();
        moneyMainEntity.setCreateTime(moneyMainDao.getCurrentTime());
        moneyMainEntity.setCurrentAuditorId("");
        moneyMainEntity.setCurrentAuditorName("");
        moneyMainEntity.setSeriesNumber("");
        moneyMainEntity.setRemark("");
        moneyMainEntity.setPayUserId("");
        moneyMainEntity.setPayDate("");
        moneyMainEntity.setPayRemark("");
        moneyMainEntity.setPayUserName("");
        moneyMainEntity.setCopierReturnReason("");
        moneyMainEntity.setPayReturnUserId("");
        moneyMainEntity.setPayReturnUserName("");
        moneyMainEntity.setPayReturnReasonType("");
        moneyMainEntity.setPayReturnReasonDesc("");
        moneyMainEntity.setRefundFlag("-1");//回款审核流默认为-1 草稿状态
        //计算总金额
        BigDecimal money = BigDecimal.ZERO;
        for (int i = 0; i < entity.getPayees().size(); i++) {
            if (entity.getPayees().get(i).getPayeeMoney() != null) {
                money = entity.getPayees().get(i).getPayeeMoney().add(money);
            }
        }
        if (moneyMainEntity.getAuditFlag().equals("0")) {
            //如果是提交申请，则设置当前审核人信息
            MoneyAuditEntity firstAuditor = entity.getAuditors().get(0);
            moneyMainEntity.setCurrentAuditorId(firstAuditor.getAuditorId());
            String[] arrAuditorName = firstAuditor.getAuditorName().split("-");
            moneyMainEntity.setCurrentAuditorName(arrAuditorName[arrAuditorName.length - 1]);
        }
        moneyMainEntity.setMoney(money);

        if (StringUtils.isBlank(moneyMainEntity.getId()) || "0".equals(moneyMainEntity.getId())) {
            moneyMainDao.add(moneyMainEntity);
        } else {
            MoneyMainEntity oldMainEntity = moneyMainDao.getEntityById(moneyMainEntity.getId());
            oldMainEntity.setType(moneyMainEntity.getType());
            oldMainEntity.setTitle(moneyMainEntity.getTitle());
            oldMainEntity.setDescription(moneyMainEntity.getDescription());
            oldMainEntity.setOrgName(moneyMainEntity.getOrgName());
            oldMainEntity.setRegionName(moneyMainEntity.getRegionName());
            oldMainEntity.setDescription(moneyMainEntity.getDescription());
            oldMainEntity.setCreateUserId(moneyMainEntity.getCreateUserId());
            oldMainEntity.setPayDate(moneyMainEntity.getPayDate());
            oldMainEntity.setRemark(moneyMainEntity.getRemark());
            oldMainEntity.setUrgentFlag(moneyMainEntity.getUrgentFlag());
            oldMainEntity.setAuditFlag(moneyMainEntity.getAuditFlag());
            oldMainEntity.setPayRemark(moneyMainEntity.getPayRemark());
            oldMainEntity.setMoney(moneyMainEntity.getMoney());
            oldMainEntity.setCreateUserName(moneyMainEntity.getCreateUserName());
            oldMainEntity.setCurrentAuditorId(moneyMainEntity.getCurrentAuditorId());
            oldMainEntity.setCurrentAuditorName(moneyMainEntity.getCurrentAuditorName());
            oldMainEntity.setSeriesNumber("");
            oldMainEntity.setRemark("");
            oldMainEntity.setPayUserId("");
            oldMainEntity.setPayDate("");
            oldMainEntity.setPayRemark("");
            oldMainEntity.setPayUserName("");
            oldMainEntity.setCopierReturnReason("");
            oldMainEntity.setPayReturnUserId("");
            oldMainEntity.setPayReturnUserName("");
            oldMainEntity.setPayReturnReasonType("");
            oldMainEntity.setPayReturnReasonDesc("");
            //回款
            oldMainEntity.setHaveRefund(moneyMainEntity.getHaveRefund());
            oldMainEntity.setEstimatedReturnDate(moneyMainEntity.getEstimatedReturnDate());
            oldMainEntity.setEstimatedReturnMoney(moneyMainEntity.getEstimatedReturnMoney());
            oldMainEntity.setReturnPayeeId(moneyMainEntity.getReturnPayeeId());
            oldMainEntity.setReturnPayeeName(moneyMainEntity.getReturnPayeeName());
            oldMainEntity.setReturnPayeeRoleName((moneyMainEntity.getReturnPayeeRoleName()));
            moneyMainDao.update(oldMainEntity);
        }

        String mainId = moneyMainEntity.getId();
        if ("0".equals(moneyMainEntity.getAuditFlag())) {
            //如果是提交申请，则设置当前审核人信息
            MoneyAuditEntity firstAuditor = entity.getAuditors().get(0);
            //保存消息到消息表t_sys_message
            MessageEntity messageEntity = new MessageEntity();
            messageEntity.setCreateUserId(moneyMainEntity.getCreateUserId());
            messageEntity.setCreateTime(messageDao.getCurrentTime());
            messageEntity.setContent(String.format(MONEY_AUDIT_AUDIT_PC,
                    firstAuditor.getAuditorName(),
                    moneyMainEntity.getType(),
                    money,
                    moneyMainEntity.getCreateUserName(),
                    DateUtils.parse(moneyMainEntity.getCreateTime(), "yyyy-MM-dd HH:mm"),
                    moneyMainEntity.getId(),
                    moneyMainEntity.getCurrentAuditorId()
            ));
            messageEntity.setMessageType(1);
            messageEntity.setMainId(mainId);
            messageEntity.setDelFlag(0);
            messageEntity.setOpenUrl("/page/apply/money/detail.html?id=" + moneyMainEntity.getId() + "&pageType=applyAudit&isAdd=0");
            messageEntity.setOpenTitle(String.format(MONEY_AUDIT_ONE, moneyMainEntity.getCreateUserName(), moneyMainEntity.getType()));
            messageDao.add(messageEntity);
            //保存第一审核人信息到消息收件人表t_sys_message_receiver
            MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
            messageReceiverEntity.setMessageId(messageEntity.getId());
            messageReceiverEntity.setUserId(moneyMainEntity.getCurrentAuditorId());
            messageReceiverEntity.setUserType(0);
            messageReceiverEntity.setReadFlag(0);
            messageReceiverDao.add(messageReceiverEntity);
            //发消息
            jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));
            //企业号:给第一审核人发送消息
            JSONObject msgObject = new JSONObject();
            msgObject.put("userIds", firstAuditor.getAuditorId());
            msgObject.put("content", String.format(MONEY_AUDIT_AUDIT,
                    firstAuditor.getAuditorName(),
                    moneyMainEntity.getType(),
                    money,
                    moneyMainEntity.getCreateUserName(),
                    DateUtils.parse(moneyMainEntity.getCreateTime(), "yyyy-MM-dd HH:mm"),
                    moneyMainEntity.getId(),
                    moneyMainEntity.getCurrentAuditorId(),messageReceiverEntity.getId()
            ));
            tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
            //推送: 给第一审核人推送红点提示
            tokenDao.sendJPushMsg(firstAuditor.getAuditorId(), String.format(MONEY_AUDIT_NOTIFY, moneyMainEntity.getCreateUserName()));
        }

        //第二步，保存收款人信息
        //删除
        moneyPayeeDao.removeByCondition(" AND FK_MONEY_ID = ? ", new String[]{mainId});
        //添加
        List<MoneyPayeeEntity> moneyPayeeEntityList = entity.getPayees();
        for (int i = 0; i < moneyPayeeEntityList.size(); i++) {
            moneyPayeeEntityList.get(i).setFkMoneyId(mainId);
            moneyPayeeEntityList.get(i).setSortNo(i);
            moneyPayeeEntityList.get(i).setUpdateUserId(moneyMainEntity.getUpdateUserId());
            this.moneyPayeeDao.add(moneyPayeeEntityList.get(i));
        }

        //第三步，保存抄送人信息
        //删除
        moneyCopierDao.removeByCondition(" AND FK_MONEY_ID = ? ", new String[]{mainId});
        //添加
        List<MoneyCopierEntity> moneyCopierEntityList = entity.getCopiers();
        for (int i = 0; i < moneyCopierEntityList.size(); i++) {
            moneyCopierEntityList.get(i).setFkMoneyId(mainId);
            this.moneyCopierDao.add(moneyCopierEntityList.get(i));


        }

        //第四步，保存审核人信息
        //删除
        moneyAuditDao.removeByCondition(" AND FK_MONEY_ID = ? ", new String[]{mainId});
        //添加
        List<MoneyAuditEntity> moneyAuditEntityList = entity.getAuditors();
        if (moneyAuditEntityList != null && moneyAuditEntityList.size() > 0) {
            for (int i = 0; i < moneyAuditEntityList.size(); i++) {
                if (!com.alibaba.dubbo.common.utils.StringUtils.isEmpty(moneyAuditEntityList.get(i).getAuditorId()) && !moneyAuditEntityList.get(i).getAuditorId().equals("0")) {
                    if (moneyMainEntity.getAuditFlag().equals("0") && i == 0) {
                        moneyAuditEntityList.get(i).setAuditFlag("0");
                    } else {
                        moneyAuditEntityList.get(i).setAuditFlag("-1");
                    }
                    moneyAuditEntityList.get(i).setFkMoneyId(mainId);
                    moneyAuditEntityList.get(i).setAuditSort(i);
                    moneyAuditEntityList.get(i).setAuditTime(null);
                    moneyAuditEntityList.get(i).setAuditAdvise("");
                    this.moneyAuditDao.add(moneyAuditEntityList.get(i));
                }
            }
        }
        //第五步,保存附件
        //删除
        attachModuleDao.removeByCondition(" AND MODULE_ID = ? ", new String[]{mainId});
        //添加
        List<AttachmentEntity> attachmentEntityList = entity.getAttaches();
        if (attachmentEntityList != null && attachmentEntityList.size() > 0) {
            for (AttachmentEntity attach : attachmentEntityList) {
                AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                attachModuleEntity.setAttachId(attach.getId());
                attachModuleEntity.setAttachModule(3);
                attachModuleEntity.setModuleId(mainId);
                attachModuleDao.add(attachModuleEntity);
                attachModuleDao.addAttach(attach.getId());
            }
        }
        result.put("mainId", mainId);
        result.put("message", jsonObjectList);
        return result;
    }

    @Override
    public String getUnDoCount(String userId) {
        Integer count = 0;
        if (userId != null && !userId.isEmpty()) {
            count = moneyMainDao.getUnDoCount(userId);
        }
        return count.toString();
    }

    @Override
    public JSONObject getByPage(String jsonData) {
        JSONObject obj = JSON.parseObject(jsonData);
        String userId = obj.getString("userId");
        String key = obj.getString("key");
        String pageType = obj.getString("pageType");
        String companyId = obj.getString("companyId");
        String auditFlag = obj.getString("auditFlag");
        String type = obj.getString("type");
        String createUserName = obj.getString("createUserName");
        String returnPayeeName = obj.getString("returnPayeeName");
        String money = obj.getString("money");
        String refundFlag = obj.getString("refundFlag");
        String haveRefund = obj.getString("haveRefund");
        int requestPage = 1;
        int pageSize = Integer.MAX_VALUE;
        if (!com.alibaba.dubbo.common.utils.StringUtils.isBlank(obj.getString("pageSize"))) {
            pageSize = obj.getInteger("pageSize");
        }
        if (!com.alibaba.dubbo.common.utils.StringUtils.isBlank(obj.getString("requestPage"))) {
            requestPage = obj.getInteger("requestPage");
        }
        boolean submitPayer = false;
        StringBuilder condition = new StringBuilder();
        List<Object> sqlArgs = new ArrayList<Object>();
        if (StringUtils.isNotEmpty(key)) {
            condition.append(" AND (DESCRIPTION LIKE '%" + key + "%' " +
                    "OR REMARK LIKE '%" + key + "%' " +
                    "OR RETURN_REMARK LIKE '%" + key + "%' " +
                    "OR ESTIMATED_RETURN_DATE LIKE '%" + key + "%' " +
                    "OR TYPE LIKE '%" + key + "%' " +
                    "OR RETURN_PAYEE_NAME LIKE '%" + key + "%' " +
                    "OR ESTIMATED_RETURN_MONEY LIKE '%" + key + "%' " +
                    "OR ACTUAL_RETURN_DATE LIKE '%" + key + "%' " +
                    "OR ACTUAL_RETURN_MONEY LIKE '%" + key + "%' " +
                    "OR PAY_REMARK LIKE '%" + key + "%') ");
        }
        if (StringUtils.isNotEmpty(auditFlag)) {
            condition.append(" AND AUDIT_FLAG = ?");
            sqlArgs.add(auditFlag);
        }
        if (StringUtils.isNotEmpty(refundFlag)) {
            condition.append(" AND REFUND_FLAG  IN (" + refundFlag + ")");
        }
        if (StringUtils.isNotEmpty(haveRefund)) {
            condition.append(" AND HAVE_REFUND = '" + haveRefund + "' ");
        }
        if (StringUtils.isNotEmpty(type)) {
            condition.append(" AND TYPE = ? ");
            sqlArgs.add(type);
        }
        if (StringUtils.isNotEmpty(createUserName)) {
            condition.append(" AND CREATE_USER_NAME LIKE  '%" + createUserName + "%'");
        }
        if (!StringUtils.isBlank(companyId)) {
            condition.append(" AND COMPANY_ID='" + companyId + "'");
        }
        if (StringUtils.isNotEmpty(money)) {
            condition.append(" AND MONEY = ? ");
            sqlArgs.add(money);
        }

        if (pageType.equals("pay")) {
            List<JSONObject> list = rightOpDao.getJSONListByCondition(" AND E_NAME = ? ", new Object[]{"submitPay"});
            if (list != null && list.size() > 0) {
                String rightOpId = list.get(0).getString("id");
                submitPayer = user2RightOpDao.exist(userId, rightOpId);
            }
            if (submitPayer) {
                condition.append(" AND AUDIT_FLAG IN ('1','3','4','6') ");
            } else {
                condition.append(" AND AUDIT_FLAG IN ('3','4','6') ");
            }

        }
        //String userIds=checkDao.getParentByUserIdForAplMoney(userId);
        //如果id是靳悦双,"201712171257484DA20FEC7F96A76B3D"  查看所有的费用
        if ("201712171257484DA20FEC7F96A76B3D".equals(userId)) {
            if (auditFlag.equals("-1")) {
                condition.append("  AND CREATE_USER_ID = '201712171257484DA20FEC7F96A76B3D' ");
            } else {
                condition.append("  AND AUDIT_FLAG <> -1 ");
            }
        } else {
            condition.append(" AND (CREATE_USER_ID = ? ");
            condition.append(" OR ( ");
            condition.append(" AUDIT_FLAG <> '-1' ");
            condition.append(" AND ( ");
            condition.append(" ID IN(SELECT FK_MONEY_ID FROM T_APL_MONEY_AUDIT WHERE AUDITOR_ID = ? AND AUDIT_FLAG <> '-1') ");
            condition.append(" OR ");
            //如果id是谈老板,抄送的不给他显示
            if ("2017121618514C22B68296F31AF8DDE2".equals(userId)) {
                condition.append(" ID IN(SELECT FK_MONEY_ID FROM T_APL_MONEY_COPIER LEFT JOIN T_APL_MONEY_MAIN ON T_APL_MONEY_COPIER.FK_MONEY_ID = T_APL_MONEY_MAIN.ID WHERE T_APL_MONEY_COPIER.COPY_PERSON_ID = ? AND( T_APL_MONEY_MAIN.AUDIT_FLAG = '2' OR T_APL_MONEY_MAIN.AUDIT_FLAG = '4'))");
            } else {
                condition.append(" ID IN(SELECT FK_MONEY_ID FROM T_APL_MONEY_COPIER WHERE COPY_PERSON_ID = ?) ");
            }
            condition.append(" OR ");
            condition.append(" ID IN(SELECT FK_MONEY_ID FROM T_APL_MONEY_PAY_AUDIT WHERE AUDITOR_ID = ? AND AUDIT_FLAG <> '1') ");
            condition.append(" OR  RETURN_PAYEE_ID = '" + userId + "'\n" +
                    "\tOR (CURRENT_AUDITOR_ID= '" + userId + "' AND REFUND_FLAG <> -1 ) ");
            condition.append("OR ID IN(\n" +
                    "SELECT t_sys_audit.MAIN_ID\n" +
                    "FROM t_sys_audit\n" +
                    "WHERE t_sys_audit.AUDITOR_ID='" + userId + "' " +
                    "AND REFUND_FLAG <> -1 )");
            //condition.append(" OR (CREATE_USER_ID IN ("+userIds+") AND AUDIT_FLAG <> '1') ");
            condition.append(" ) ");
            condition.append(" ) ");
            if (pageType.equals("pay") && submitPayer) {
                List<JSONObject> listUsers = userDao.getViewJSONListByCondition(" and id = ?", new Object[]{userId});
                List<String> listCompanyIds = new ArrayList<>();
                for (int i = 0; i < listUsers.size(); i++) {
                    String userCompanyId = listUsers.get(i).getString("companyId");
                    listCompanyIds.add(userCompanyId);
                    companyDao.getChildrenIds(userCompanyId, listCompanyIds);
                }
                String companyIds = "";
                for (int i = 0; i < listCompanyIds.size(); i++) {
                    companyIds += "'" + listCompanyIds.get(i) + "',";
                }
                companyIds = companyIds.substring(0, companyIds.length() - 1);
                condition.append(" OR COMPANY_ID IN(" + companyIds + ") ");
            }
            condition.append(" ) ");
            sqlArgs.add(userId);
            sqlArgs.add(userId);
            sqlArgs.add(userId);
            sqlArgs.add(userId);
        }
        List<JSONObject> records = this.moneyMainDao.getJSONListByPage(userId, condition.toString(), sqlArgs.toArray(), requestPage, pageSize, haveRefund);
        int recordCount = this.moneyMainDao.getPageCount(condition.toString(), sqlArgs.toArray());
        //如果整除表示正好分N页，如果不能整除在N页的基础上+1页
        int pageCount = recordCount % pageSize == 0 ? recordCount / pageSize : (recordCount / pageSize) + 1;
        JSONObject objPager = new JSONObject();
        objPager.put("recordCount", recordCount);
        objPager.put("pageCount", pageCount);
        //返回
        JSONObject objResult = new JSONObject();
        objResult.put("records", records);
        objResult.put("pager", objPager);
        return objResult;
    }

    @Override
    public JSONObject getById(String id) {
        MoneyEntity moneyEntity = new MoneyEntity();
        moneyEntity.setMain(this.moneyMainDao.getEntityById(id));
        moneyEntity.setPayees(moneyPayeeDao.getEntityListByCondition(" AND FK_MONEY_ID = ? AND LOG_FLAG=0 ORDER BY SORT_NO ", new Object[]{id}));
        moneyEntity.setCopiers(this.moneyCopierDao.getEntityListByCondition(" AND FK_MONEY_ID = ? ", new Object[]{id}));
        moneyEntity.setAuditors(this.moneyAuditDao.getEntityListByCondition(" AND FK_MONEY_ID = ? ORDER BY AUDIT_SORT ", new Object[]{id}));
        moneyEntity.setHistorys(this.auditHistoryDao.getEntityListByCondition(" AND MAIN_ID =? AND AUDIT_FLAG=2 ORDER BY AUDIT_TIME DESC", new Object[]{id}));
        return (JSONObject) JSON.toJSON(moneyEntity);
    }

    @Override
    public JSONObject getByIdForRefund(String jsonData) {
        //-1 跟踪人第一审核草稿（上级） 0审核中 1通过 2驳回
        JSONObject jsonObject = JSON.parseObject(jsonData);
        String id = jsonObject.getString("id");
        String userId = jsonObject.getString("userId");
        MoneyEntity moneyEntity = new MoneyEntity();
        MoneyMainEntity moneyMainEntity = this.moneyMainDao.getEntityById(id);
        moneyEntity.setMain(moneyMainEntity);
        List<AuditEntity> auditEntityList = (List<AuditEntity>) (Object) auditDao.getIBaseEntityByCondition(" AND MAIN_ID = ? ORDER BY AUDIT_SORT", new Object[]{id});
        if (null == auditEntityList || auditEntityList.size() <= 0) {
            auditEntityList = getRefundAudits(moneyMainEntity.getReturnPayeeId(), id);
        }
        moneyEntity.setAuditList(auditEntityList);
        moneyEntity.setHistorys(this.auditHistoryDao.getEntityListByCondition(" AND MAIN_ID =? AND (AUDIT_FLAG=2 OR AUDIT_FLAG=6) AND AUDIT_TYPE=9 ORDER BY AUDIT_TIME DESC", new Object[]{id}));
        return (JSONObject) JSON.toJSON(moneyEntity);
    }

    @Override
    public JSONObject applyAudit(String id, String userId, String auditFlag, String advise) {
        JSONObject result = new JSONObject();
        List<JSONObject> jsonObjectList = new ArrayList<>();
        //保存历史审核信息
        AuditHistoryEntity auditHistoryEntity = new AuditHistoryEntity();
        auditHistoryEntity.setMainId(id);
        auditHistoryEntity.setAuditorId(userId);
        JSONObject user = userDao.getJSONById(userId);
        auditHistoryEntity.setAuditorName(user.getString("name"));
        auditHistoryEntity.setAuditFlag(auditFlag);
        auditHistoryEntity.setAuditAdvise(advise);
        auditHistoryEntity.setAuditType(1);
        auditHistoryEntity.setAuditTime(moneyAuditDao.getCurrentTime());
        auditHistoryDao.add(auditHistoryEntity);
        //根据id获取主表信息
        MoneyMainEntity mainEntity = moneyMainDao.getEntityById(id);
        //根据id获取审核信息
        List<MoneyAuditEntity> auditEntityList = moneyAuditDao.getEntityListByCondition(" AND FK_MONEY_ID = ? ORDER BY AUDIT_SORT ", new Object[]{id});
        //根据id获取消息信息
        List<MessageEntity> messageEntityList = (List<MessageEntity>) (Object) messageDao.getIBaseEntityByCondition("AND MAIN_ID=? ", new Object[]{id});
        MessageEntity message = null;
        if (null != messageEntityList && messageEntityList.size() > 0) {
            message = messageEntityList.get(0);
        }
        //根据id获取消息发送表信息
        if (null != message) {
            List<MessageReceiverEntity> messageReceiverEntityLists = (List<MessageReceiverEntity>) (Object) messageReceiverDao.getIBaseEntityByCondition("AND MESSAGE_ID=? ", new Object[]{message.getId()});
        }
        MoneyAuditEntity auditEntityNow = null;
        for (int i = 0; i < auditEntityList.size(); i++) {
            if (auditEntityList.get(i).getAuditorId().equals(userId)) {
                //如果审核人==当前审核人
                auditEntityNow = auditEntityList.get(i);
                auditEntityNow.setAuditFlag(auditFlag);
                auditEntityNow.setAuditTime(moneyPayAuditDao.getCurrentTime());
                auditEntityNow.setAuditAdvise(advise);
                moneyAuditDao.update(auditEntityNow);

                if (auditFlag.equals("1")) {

                    //企业号：审核通过，发送消息给当前审核人
//                    JSONObject msgAuditObject = new JSONObject();
//                    msgAuditObject.put("userIds", auditEntityNow.getAuditorId());
//                    msgAuditObject.put("content", String.format(MONEY_AUDIT_PASSONE,
//                            auditEntityNow.getAuditorName(),
//                            mainEntity.getType(),
//                            mainEntity.getMoney(),
//                            mainEntity.getCreateUserName(),
//                            DateUtils.parse(mainEntity.getCreateTime(), "yyyy-MM-dd HH:mm"),
//                            mainEntity.getId(),
//                            mainEntity.getCurrentAuditorId()));
//                    tokenDao.sendTextMsg(JSON.toJSONString(msgAuditObject));

//                    //审核通过，发送消息给当前审核人，保存消息到消息表t_sys_message
//                    MessageEntity msgAuditNameEntity = new MessageEntity();
//                    msgAuditNameEntity.setCreateUserId(mainEntity.getCreateUserId());
//                    msgAuditNameEntity.setCreateTime(messageDao.getCurrentTime());
//                    msgAuditNameEntity.setContent(String.format(MONEY_AUDIT_PASSONE,
//                            auditEntityNow.getAuditorName(),
//                            mainEntity.getType(),
//                            mainEntity.getMoney(),
//                            mainEntity.getCreateUserName(),
//                            DateUtils.parse(mainEntity.getCreateTime(), "yyyy-MM-dd HH:mm"),
//                            mainEntity.getId(),
//                            mainEntity.getCurrentAuditorId()));
//                    msgAuditNameEntity.setMessageType(0);
//                    msgAuditNameEntity.setMainId(id);
//                    msgAuditNameEntity.setDelFlag(0);
//                    msgAuditNameEntity.setOpenUrl("/page/apply/money/detail.html?id=" + mainEntity.getId() + "&pageType=browser&isAdd=0");
//                    msgAuditNameEntity.setOpenTitle(String.format(MONEY_AUDIT_FOUR, mainEntity.getCreateUserName(), mainEntity.getType()));
//                    messageDao.add(msgAuditNameEntity);
//
//                    //审核通过，发送消息给当前审核人，保存消息到表t_sys_message_receiver
//                    MessageReceiverEntity msgReceiverAuditEntity = new MessageReceiverEntity();
//                    msgReceiverAuditEntity.setMessageId(msgAuditNameEntity.getId());
//                    msgReceiverAuditEntity.setUserId(mainEntity.getCurrentAuditorId());
//                    msgReceiverAuditEntity.setUserType(0);
//                    msgReceiverAuditEntity.setReadFlag(1);
//                    messageReceiverDao.add(msgReceiverAuditEntity);
//
//                    //发消息1
//                    //jsonObjectList.add(getMessage(msgAuditNameEntity, msgReceiverAuditEntity));

                    //审核通过，发送消息给申请人，保存消息到消息表t_sys_message
                    MessageEntity msgAuditEntity = new MessageEntity();
                    msgAuditEntity.setCreateUserId(mainEntity.getCreateUserId());
                    msgAuditEntity.setCreateTime(messageDao.getCurrentTime());
                    msgAuditEntity.setContent(String.format(MONEY_AUDIT_PASSONE,
                            auditEntityNow.getAuditorName(),
                            mainEntity.getType(),
                            mainEntity.getMoney(),
                            mainEntity.getCreateUserName(),
                            DateUtils.parse(mainEntity.getCreateTime(), "yyyy-MM-dd HH:mm"),
                            mainEntity.getId(),
                            mainEntity.getCurrentAuditorId()));
                    msgAuditEntity.setMessageType(0);
                    msgAuditEntity.setMainId(id);
                    msgAuditEntity.setDelFlag(0);
                    msgAuditEntity.setOpenUrl("/page/apply/money/detail.html?id=" + mainEntity.getId() + "&pageType=browser&isAdd=0");
                    msgAuditEntity.setOpenTitle(String.format(MONEY_AUDIT_TWO, mainEntity.getType(), auditEntityNow.getAuditorName()));
                    messageDao.add(msgAuditEntity);

                    //审核通过，发送消息给申请人，保存消息到表t_sys_message_receiver
                    MessageReceiverEntity msgReceiverEntity = new MessageReceiverEntity();
                    msgReceiverEntity.setMessageId(msgAuditEntity.getId());
                    msgReceiverEntity.setUserId(mainEntity.getCreateUserId());
                    msgReceiverEntity.setUserType(2);
                    msgReceiverEntity.setReadFlag(0);
                    messageReceiverDao.add(msgReceiverEntity);

                    //发消息1
                    jsonObjectList.add(getMessage(msgAuditEntity, msgReceiverEntity));

                    if (i == auditEntityList.size() - 1) {
                        //如果是最后一个审核人,跳过申请付款,直接待付款
                        mainEntity.setAuditFlag("4");
                        mainEntity.setCurrentAuditorId("");
                        mainEntity.setCurrentAuditorName("");
                        mainEntity.setSeriesNumber(this.getApplySerNum(mainEntity.getCompanyId(), mainEntity.getCreateTime()));
                        moneyMainDao.update(mainEntity);

                        //企业号: 最后一个审核通过,发送消息给申请人
                        JSONObject msgObject = new JSONObject();
                        msgObject.put("userIds", mainEntity.getCreateUserId());
                        msgObject.put("content", String.format(MONEY_AUDIT_PASS,
                                mainEntity.getCreateUserName(),
                                mainEntity.getType(),
                                mainEntity.getMoney(),
                                auditEntityNow.getAuditorName(),
                                DateUtils.parse(auditEntityNow.getAuditTime(), "yyyy-MM-dd HH:mm")));
                        tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

//                        //最后一个审核通过，发送消息给申请人，保存消息到消息表t_sys_message
//                        MessageEntity messageEntity = new MessageEntity();
//                        messageEntity.setCreateUserId(mainEntity.getCreateUserId());
//                        messageEntity.setCreateTime(messageDao.getCurrentTime());
//                        messageEntity.setContent(String.format(MONEY_AUDIT_PASS,
//                                mainEntity.getCreateUserName(),
//                                mainEntity.getType(),
//                                mainEntity.getMoney(),
//                                auditEntityNow.getAuditorName(),
//                                DateUtils.parse(auditEntityNow.getAuditTime(), "yyyy-MM-dd HH:mm")));
//                        messageEntity.setMessageType(0);
//                        messageEntity.setMainId(id);
//                        messageEntity.setDelFlag(0);
//                        messageEntity.setOpenUrl("/page/apply/money/detail.html?id=" + mainEntity.getId() + "&pageType=browser&isAdd=0");
//                        messageEntity.setOpenTitle(String.format(MONEY_AUDIT_TWO, mainEntity.getType(), auditEntityNow.getAuditorName()));
//                        messageDao.add(messageEntity);
//
//                        //最后一个审核通过，发送消息给申请人，保存消息到表t_sys_message_receiver
//                        MessageReceiverEntity msgEntity = new MessageReceiverEntity();
//                        msgEntity.setMessageId(messageEntity.getId());
//                        msgEntity.setUserId(mainEntity.getCreateUserId());
//                        msgEntity.setUserType(2);
//                        msgEntity.setReadFlag(0);
//                        messageReceiverDao.add(msgEntity);
//
//                        //发消息2
//                        jsonObjectList.add(getMessage(messageEntity, msgEntity));

                    } else {
                        MoneyAuditEntity auditEntityNext = auditEntityList.get(i + 1);
                        auditEntityNext.setAuditFlag("0");
                        moneyAuditDao.update(auditEntityNext);

                        mainEntity.setCurrentAuditorId(auditEntityNext.getAuditorId());
                        String[] arrAuditorName = auditEntityNext.getAuditorName().split("-");
                        mainEntity.setCurrentAuditorName(arrAuditorName[arrAuditorName.length - 1]);
                        moneyMainDao.update(mainEntity);

                        //企业号: 审核通过,发送消息给申请人
                        JSONObject msgObject = new JSONObject();
                        msgObject.put("userIds", mainEntity.getCreateUserId());
                        msgObject.put("content", String.format(MONEY_AUDIT_PASS,
                                mainEntity.getCreateUserName(),
                                mainEntity.getType(),
                                mainEntity.getMoney(),
                                auditEntityNow.getAuditorName(),
                                DateUtils.parse(auditEntityNow.getAuditTime(), "yyyy-MM-dd HH:mm")));
                        tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
                        MessageEntity messageNextEntity = new MessageEntity();
                        messageNextEntity.setCreateUserId(mainEntity.getCreateUserId());
                        messageNextEntity.setCreateTime(messageDao.getCurrentTime());
                        messageNextEntity.setContent(String.format(MONEY_AUDIT_AUDIT_PC,
                                auditEntityNext.getAuditorName(),
                                mainEntity.getType(),
                                mainEntity.getMoney(),
                                mainEntity.getCreateUserName(),
                                DateUtils.parse(mainEntity.getCreateTime(), "yyyy-MM-dd HH:mm"),
                                mainEntity.getId(),
                                mainEntity.getCurrentAuditorId()));
                        messageNextEntity.setMessageType(1);
                        messageNextEntity.setMainId(id);
                        messageNextEntity.setDelFlag(0);
                        messageNextEntity.setOpenUrl("/page/apply/money/detail.html?id=" + mainEntity.getId() + "&pageType=applyAudit&isAdd=0");
                        messageNextEntity.setOpenTitle(String.format(MONEY_AUDIT_ONE, mainEntity.getCreateUserName(), mainEntity.getType()));
                        messageDao.add(messageNextEntity);

                        //保存消息到消息收件人表t_sys_message_receiver
                        MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
                        messageReceiverEntity.setMessageId(messageNextEntity.getId());
                        messageReceiverEntity.setUserId(mainEntity.getCurrentAuditorId());
                        messageReceiverEntity.setUserType(0);
                        messageReceiverEntity.setReadFlag(0);
                        messageReceiverDao.add(messageReceiverEntity);

                        //发消息4
                        jsonObjectList.add(getMessage(messageNextEntity, messageReceiverEntity));
                        //企业号: 给下一审核人发消息
                        JSONObject msgNextObject = new JSONObject();
                        msgNextObject.put("userIds", auditEntityNext.getAuditorId());
                        msgNextObject.put("content", String.format(MONEY_AUDIT_AUDIT,
                                auditEntityNext.getAuditorName(),
                                mainEntity.getType(),
                                mainEntity.getMoney(),
                                mainEntity.getCreateUserName(),
                                DateUtils.parse(mainEntity.getCreateTime(), "yyyy-MM-dd HH:mm"),
                                mainEntity.getId(),
                                mainEntity.getCurrentAuditorId(),messageReceiverEntity.getId()
                        ));
                        tokenDao.sendTextMsg(JSON.toJSONString(msgNextObject));
                        //推送: 给下一审核人推送红点提示
                        tokenDao.sendJPushMsg(auditEntityNext.getAuditorId(), String.format(MONEY_AUDIT_NOTIFY, mainEntity.getCreateUserName()));
                    }
                } else if (auditFlag.equals("2")) {
                    mainEntity.setAuditFlag(auditFlag);
                    if (advise.contains("其他原因")) {
                        mainEntity.setReturnType("1");
                    } else {
                        mainEntity.setReturnType("0");
                    }
                    mainEntity.setCurrentAuditorId("");
                    mainEntity.setCurrentAuditorName("");
                    moneyMainDao.update(mainEntity);

                    //企业号：审核驳回，发送消息给当前审核人
//                    JSONObject msgAuditObject = new JSONObject();
//                    msgAuditObject.put("userIds", auditEntityNow.getAuditorId());
//                    msgAuditObject.put("content", String.format(MONEY_AUDIT_REJECTONE,
//                            auditEntityNow.getAuditorName(),
//                            mainEntity.getType(),
//                            mainEntity.getMoney(),
//                            mainEntity.getCreateUserName(),
//                            DateUtils.parse(mainEntity.getCreateTime(), "yyyy-MM-dd HH:mm"),
//                            mainEntity.getId(),
//                            mainEntity.getCurrentAuditorId()));
//                    tokenDao.sendTextMsg(JSON.toJSONString(msgAuditObject));

//                    //审核驳回，发送消息给当前审核人，保存消息到消息表t_sys_message
//                    MessageEntity messageEntity = new MessageEntity();
//                    messageEntity.setCreateUserId(mainEntity.getCreateUserId());
//                    messageEntity.setCreateTime(messageDao.getCurrentTime());
//                    messageEntity.setContent(String.format(MONEY_AUDIT_REJECT,
//                            mainEntity.getCreateUserName(),
//                            mainEntity.getType(),
//                            mainEntity.getMoney(),
//                            auditEntityNow.getAuditAdvise(),
//                            auditEntityNow.getAuditorName(),
//                            DateUtils.parse(auditEntityNow.getAuditTime(), "yyyy-MM-dd HH:mm")));
//                    messageEntity.setMessageType(0);
//                    messageEntity.setMainId(id);
//                    messageEntity.setDelFlag(0);
//                    messageEntity.setOpenUrl("/page/apply/money/detail.html?id=" + mainEntity.getId() + "&pageType=browser&isAdd=0");
//                    messageEntity.setOpenTitle(String.format(MONEY_AUDIT_FIVE, mainEntity.getCreateUserName(), mainEntity.getType()));
//                    messageDao.add(messageEntity);
//
//                    //审核驳回，发送消息给当前审核人,保存消息到消息收件人表t_sys_message_receiver
//                    MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
//                    messageReceiverEntity.setMessageId(messageEntity.getId());
//                    messageReceiverEntity.setUserId(auditEntityNow.getAuditorId());
//                    messageReceiverEntity.setUserType(0);
//                    messageReceiverEntity.setReadFlag(0);
//                    messageReceiverDao.add(messageReceiverEntity);
//
//                    //发消息6
//                   // jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));

                    //审核人驳回
                    //企业号:发消息通知申请人  (不发送给抄送人)
                    JSONObject msgObject = new JSONObject();
                    msgObject.put("userIds", mainEntity.getCreateUserId());
                    msgObject.put("content", String.format(MONEY_AUDIT_REJECT,
                            mainEntity.getCreateUserName(),
                            mainEntity.getType(),
                            mainEntity.getMoney(),
                            auditEntityNow.getAuditAdvise(),
                            auditEntityNow.getAuditorName(),
                            DateUtils.parse(auditEntityNow.getAuditTime(), "yyyy-MM-dd HH:mm")));
                    tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

                    //审核驳回，发送消息给申请人，保存消息到消息表t_sys_message
                    MessageEntity messageCreateEntity = new MessageEntity();
                    messageCreateEntity.setCreateUserId(mainEntity.getCreateUserId());
                    messageCreateEntity.setCreateTime(messageDao.getCurrentTime());
                    messageCreateEntity.setContent(String.format(MONEY_AUDIT_REJECT,
                            mainEntity.getCreateUserName(),
                            mainEntity.getType(),
                            mainEntity.getMoney(),
                            auditEntityNow.getAuditAdvise(),
                            auditEntityNow.getAuditorName(),
                            DateUtils.parse(auditEntityNow.getAuditTime(), "yyyy-MM-dd HH:mm")));
                    messageCreateEntity.setMessageType(0);
                    messageCreateEntity.setMainId(id);
                    messageCreateEntity.setDelFlag(0);
                    messageCreateEntity.setOpenUrl("/page/apply/money/detail.html?id=" + mainEntity.getId() + "&pageType=browser&isAdd=0");
                    messageCreateEntity.setOpenTitle(String.format(MONEY_AUDIT_THREE, mainEntity.getType(), auditEntityNow.getAuditorName()));
                    messageDao.add(messageCreateEntity);

                    //审核驳回，发送消息给申请人,保存消息到消息收件人表t_sys_message_receiver
                    MessageReceiverEntity messageCreateReceiverEntity = new MessageReceiverEntity();
                    messageCreateReceiverEntity.setMessageId(messageCreateEntity.getId());
                    messageCreateReceiverEntity.setUserId(mainEntity.getCreateUserId());
                    messageCreateReceiverEntity.setUserType(2);
                    messageCreateReceiverEntity.setReadFlag(0);
                    messageReceiverDao.add(messageCreateReceiverEntity);

                    //发消息5
                    jsonObjectList.add(getMessage(messageCreateEntity, messageCreateReceiverEntity));

                } else {
                    mainEntity.setAuditFlag(auditFlag);
                    mainEntity.setCurrentAuditorId("");
                    mainEntity.setCurrentAuditorName("");
                    moneyMainDao.update(mainEntity);
                }
                break;
            }
        }
        //发消息
        result.put("message", jsonObjectList);
        result.put("flag", true);
        return result;
    }

    @Override
    public Boolean submitPayAudit(String jsonString) {
        JSONObject obj = JSON.parseObject(jsonString);
        String ids = obj.getString("ids");
        JSONArray arrPayAuditors = obj.getJSONArray("payAuditors");
        //JSONArray arrPayers = obj.getJSONArray("payers");
        String[] arrIds = ids.split(",");
        StringBuilder sbIds = new StringBuilder();
        for (int i = 0; i < arrIds.length; i++) {
            sbIds.append("'" + arrIds[i] + "',");
        }
        String resultIds = sbIds.toString().substring(0, sbIds.toString().length() - 1);
        //删除旧数据
        moneyPayAuditDao.removeByCondition(" AND FK_MONEY_ID IN(" + resultIds + ")", new String[]{});
        moneyPayerDao.removeByCondition(" AND FK_MONEY_ID IN(" + resultIds + ")", new String[]{});

        for (int i = 0; i < arrIds.length; i++) {
            MoneyMainEntity mainEntity = moneyMainDao.getEntityById(arrIds[i]);
            for (int j = 0; j < arrPayAuditors.size(); j++) {
                String auditorId = ((JSONObject) arrPayAuditors.get(j)).getString("auditorId");
                if (!com.alibaba.dubbo.common.utils.StringUtils.isEmpty(auditorId) && !auditorId.equals("0")) {
                    String auditorName = ((JSONObject) arrPayAuditors.get(j)).getString("auditorName");
                    MoneyPayAuditEntity moneyPayAuditEntity = new MoneyPayAuditEntity();
                    moneyPayAuditEntity.setFkMoneyId(arrIds[i]);
                    moneyPayAuditEntity.setAuditorId(auditorId);
                    moneyPayAuditEntity.setAuditorName(auditorName);
                    moneyPayAuditEntity.setAuditSort(j);
                    if (j == 0) {
                        moneyPayAuditEntity.setAuditFlag("3");
                        mainEntity.setAuditFlag("3");
                        mainEntity.setCurrentAuditorId(auditorId);
                        String[] arrAuditorName = auditorName.split("-");
                        mainEntity.setCurrentAuditorName(arrAuditorName[arrAuditorName.length - 1]);
                        moneyMainDao.update(mainEntity);

                        //企业号:第一个付款审核人发消息
                        JSONObject msgObject = new JSONObject();
                        msgObject.put("userIds", mainEntity.getCurrentAuditorId());
                        msgObject.put("content", String.format(MONEY_PAY_AUDIT,
                                mainEntity.getCurrentAuditorName(),
                                mainEntity.getType(),
                                mainEntity.getMoney(),
                                mainEntity.getCreateUserName(),
                                DateUtils.parse(mainEntity.getCreateTime(), "yyyy-MM-dd HH:mm")));
                    } else {
                        moneyPayAuditEntity.setAuditFlag("1");
                    }
                    moneyPayAuditDao.add(moneyPayAuditEntity);
                }
            }
            /*
            for (int j = 0; j < arrPayers.size(); j++) {
                String payerId = ((JSONObject) arrPayers.get(j)).getString("payerId");
                String payerName = ((JSONObject) arrPayers.get(j)).getString("payerName");
                MoneyPayerEntity moneyPayerEntity = new MoneyPayerEntity();
                moneyPayerEntity.setFkMoneyId(arrIds[i]);
                moneyPayerEntity.setPayerId(payerId);
                moneyPayerEntity.setPayerName(payerName);
                moneyPayerDao.add(moneyPayerEntity);
            }*/
        }
        return true;
    }

    /**
     * 生成用款流水号
     *
     * @return
     */
    private String getApplySerNum(String companyId, Date createTime) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String date = simpleDateFormat.format(createTime);
        StringBuilder condition = new StringBuilder();
        List<Object> sqlArgs = new ArrayList<Object>();
        condition.append(" AND AUDIT_FLAG IN (1,4,6)");
        condition.append(" AND COMPANY_ID=? ");
        sqlArgs.add(companyId);
        condition.append(" AND CREATE_TIME like ?");
        sqlArgs.add("%" + date + "%");
        Integer applyCount = moneyMainDao.getPageCount(condition.toString(), sqlArgs.toArray());
        JSONObject company = companyDao.getJSONById(companyId);
        String companyName = company.getString("name");
        companyName = companyName.replace("灜", "一");
        String companyPy = toPinyin(companyName).toUpperCase();
        String result = null;
        SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMdd");
        result = sdf.format(createTime);
        return companyPy + result + String.format("%04d", applyCount + 1);
    }

    public static String toPinyin(String str) {
        String convert = "";
        for (int i = 0; i < str.length(); i++) {
            char word = str.charAt(i);
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null) {
                convert += pinyinArray[0].charAt(0);
            } else {
                convert += word;
            }
        }
        return convert;
    }

    @Override
    public JSONObject payAudit(String ids, String userId, String auditFlag, String advise) {
        JSONObject result = new JSONObject();
        List<JSONObject> jsonObjectList = new ArrayList<>();
        String[] arrIds = ids.split(",");
        for (int i = 0; i < arrIds.length; i++) {
            String id = arrIds[i];
            //根据id获取主表信息
            MoneyMainEntity mainEntity = moneyMainDao.getEntityById(id);
            //根据id获取审核信息
            List<MoneyPayAuditEntity> moneyPayAuditEntityList = moneyPayAuditDao.getEntityListByCondition(" AND FK_MONEY_ID = ? ORDER BY AUDIT_SORT ", new Object[]{id});
            MoneyPayAuditEntity moneyPayAuditEntityNow = null;
            for (int j = 0; j < moneyPayAuditEntityList.size(); j++) {
                if (moneyPayAuditEntityList.get(j).getAuditorId().equals(userId)) {
                    //如果审核人==当前审核人
                    moneyPayAuditEntityNow = moneyPayAuditEntityList.get(j);
                    moneyPayAuditEntityNow.setAuditFlag(auditFlag);
                    moneyPayAuditEntityNow.setAuditTime(moneyMainDao.getCurrentTime());
                    moneyPayAuditEntityNow.setAuditAdvise(advise);
                    moneyPayAuditDao.update(moneyPayAuditEntityNow);

                    //企业号:付款审核驳回发消息给申请人
                    JSONObject msgObject = new JSONObject();
                    msgObject.put("userIds", mainEntity.getCreateUserId());
                    if ("5".equals(auditFlag)) {
                        //审核驳回
                        msgObject.put("content", String.format(MONEY_AUDIT_REJECT,
                                mainEntity.getCreateUserName(),
                                mainEntity.getType(),
                                mainEntity.getMoney(),
                                moneyPayAuditEntityNow.getAuditAdvise(),
                                moneyPayAuditEntityNow.getAuditorName(),
                                DateUtils.parse(moneyPayAuditEntityNow.getAuditTime(), "yyyy-MM-dd HH:mm")));
                        tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

                        //付款审核驳回发消息给申请人，保存消息到消息表t_sys_message
                        MessageEntity messageEntity = new MessageEntity();
                        messageEntity.setCreateUserId(mainEntity.getCreateUserId());
                        messageEntity.setCreateTime(messageDao.getCurrentTime());
                        messageEntity.setContent(String.format(MONEY_AUDIT_REJECT,
                                mainEntity.getCreateUserName(),
                                mainEntity.getType(),
                                mainEntity.getMoney(),
                                moneyPayAuditEntityNow.getAuditAdvise(),
                                moneyPayAuditEntityNow.getAuditorName(),
                                DateUtils.parse(moneyPayAuditEntityNow.getAuditTime(), "yyyy-MM-dd HH:mm")));
                        messageEntity.setMessageType(0);
                        messageEntity.setMainId(mainEntity.getId());
                        messageEntity.setDelFlag(0);
                        messageEntity.setOpenUrl("/page/apply/money/detail.html?id=" + mainEntity.getId() + "&pageType=browser&isAdd=0");
                        messageEntity.setOpenTitle(String.format(MONEY_AUDIT_THREE, mainEntity.getType(), moneyPayAuditEntityNow.getAuditorName()));
                        messageDao.add(messageEntity);

                        //付款审核驳回发消息给申请人,保存消息到消息收件人表t_sys_message_receiver
                        MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
                        messageReceiverEntity.setMessageId(messageEntity.getId());
                        messageReceiverEntity.setUserId(mainEntity.getCreateUserId());
                        messageReceiverEntity.setUserType(2);
                        messageReceiverEntity.setReadFlag(0);
                        messageReceiverDao.add(messageReceiverEntity);

                        //发消息
                        jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));

                    }

                    if (auditFlag.equals("4")) {
                        if (j == moneyPayAuditEntityList.size() - 1) {
                            //如果是最后一个审核人
                            mainEntity.setAuditFlag(auditFlag);
                            mainEntity.setCurrentAuditorId("");
                            mainEntity.setCurrentAuditorName("");
                            moneyMainDao.update(mainEntity);

                        } else {
                            MoneyPayAuditEntity payAuditEntityNext = moneyPayAuditEntityList.get(j + 1);
                            payAuditEntityNext.setAuditFlag("3");
                            moneyPayAuditDao.update(payAuditEntityNext);

                            mainEntity.setCurrentAuditorId(payAuditEntityNext.getAuditorId());
                            String[] arrAuditorName = payAuditEntityNext.getAuditorName().split("-");
                            mainEntity.setCurrentAuditorName(arrAuditorName[arrAuditorName.length - 1]);
                            moneyMainDao.update(mainEntity);

                            //企业号: 发送消息给下一个付款审核人
                            JSONObject msgNextObject = new JSONObject();
                            msgNextObject.put("userIds", payAuditEntityNext.getAuditorId());
                            msgNextObject.put("content", String.format(MONEY_PAY_AUDIT,
                                    payAuditEntityNext.getAuditorName(),
                                    mainEntity.getType(),
                                    mainEntity.getMoney(),
                                    mainEntity.getCreateUserName(),
                                    DateUtils.parse(mainEntity.getCreateTime(), "yyyy-MM-dd HH:mm")));
                            tokenDao.sendTextMsg(JSON.toJSONString(msgNextObject));

                            //发送消息给下一个付款审核人，保存消息到消息表t_sys_message
                            MessageEntity messageEntity = new MessageEntity();
                            messageEntity.setCreateUserId(mainEntity.getCreateUserId());
                            messageEntity.setCreateTime(messageDao.getCurrentTime());
                            messageEntity.setContent(String.format(MONEY_PAY_AUDIT,
                                    payAuditEntityNext.getAuditorName(),
                                    mainEntity.getType(),
                                    mainEntity.getMoney(),
                                    mainEntity.getCreateUserName(),
                                    DateUtils.parse(mainEntity.getCreateTime(), "yyyy-MM-dd HH:mm")));
                            messageEntity.setMessageType(1);
                            messageEntity.setMainId(mainEntity.getId());
                            messageEntity.setDelFlag(0);
                            messageEntity.setOpenUrl("/page/apply/money/detail.html?id=" + mainEntity.getId() + "&pageType=applyAudit&isAdd=0");
                            messageEntity.setOpenTitle(String.format(MONEY_AUDIT_ONE, mainEntity.getCreateUserName(), mainEntity.getType()));
                            messageDao.add(messageEntity);

                            //发送消息给下一个付款审核人,保存消息到消息收件人表t_sys_message_receiver
                            MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
                            messageReceiverEntity.setMessageId(messageEntity.getId());
                            messageReceiverEntity.setUserId(payAuditEntityNext.getAuditorId());
                            messageReceiverEntity.setUserType(0);
                            messageReceiverEntity.setReadFlag(0);
                            messageReceiverDao.add(messageReceiverEntity);

                            //发消息
                            jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));
                        }
                    } else {
                        mainEntity.setAuditFlag(auditFlag);
                        mainEntity.setCurrentAuditorId("");
                        mainEntity.setCurrentAuditorName("");
                        moneyMainDao.update(mainEntity);
                    }
                    break;
                }
            }

        }
        result.put("message", jsonObjectList);
        result.put("flag", true);
        return result;
    }

    @Override
    public JSONObject payMoney(String id, String payUserId, String payRemark, String payUserName) {
        JSONObject result = new JSONObject();
        List<JSONObject> jsonObjectList = new ArrayList<>();
        MoneyMainEntity moneyMainEntity = moneyMainDao.getEntityById(id);
        moneyMainEntity.setAuditFlag("6");
        moneyMainEntity.setPayRemark(payRemark);
        moneyMainEntity.setPayUserId(payUserId);
        moneyMainEntity.setPayUserName(payUserName);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        moneyMainEntity.setPayDate(formatter.format(moneyMainDao.getCurrentTime()));
        moneyMainDao.update(moneyMainEntity);

        //企业号: 付款成功后给申请人发消息
        JSONObject msgNextObject = new JSONObject();
        msgNextObject.put("userIds", moneyMainEntity.getCreateUserId());
        msgNextObject.put("content", String.format(MONEY_PAY_PASS,
                moneyMainEntity.getCreateUserName(),
                moneyMainEntity.getType(),
                moneyMainEntity.getMoney(),
                moneyMainEntity.getPayUserName(),
                moneyMainEntity.getPayDate()));
        tokenDao.sendTextMsg(JSON.toJSONString(msgNextObject));

        //付款成功后给申请人发消息，保存消息到消息表t_sys_message
        MessageEntity messageEntity = new MessageEntity();
        messageEntity.setCreateUserId(moneyMainEntity.getCreateUserId());
        messageEntity.setCreateTime(messageDao.getCurrentTime());
        messageEntity.setContent(String.format(MONEY_PAY_PASS,
                moneyMainEntity.getCreateUserName(),
                moneyMainEntity.getType(),
                moneyMainEntity.getMoney(),
                moneyMainEntity.getPayUserName(),
                moneyMainEntity.getPayDate()));
        messageEntity.setMessageType(0);
        messageEntity.setMainId(id);
        messageEntity.setDelFlag(0);
        messageEntity.setOpenUrl("/page/apply/money/detail.html?id=" + moneyMainEntity.getId() + "&pageType=browser&isAdd=0");
        messageEntity.setOpenTitle(String.format(MONEY_PAY_ONE, moneyMainEntity.getType(), moneyMainEntity.getPayUserName()));
        messageDao.add(messageEntity);

        //付款成功后给申请人发消息,保存消息到消息收件人表t_sys_message_receiver
        MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
        messageReceiverEntity.setMessageId(messageEntity.getId());
        messageReceiverEntity.setUserId(moneyMainEntity.getCreateUserId());
        messageReceiverEntity.setUserType(2);
        messageReceiverEntity.setReadFlag(0);
        messageReceiverDao.add(messageReceiverEntity);

        //发消息
        jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));

        /*//企业号: 付款成功后给申请人发消息
        msgNextObject = new JSONObject();
        msgNextObject.put("userIds", moneyMainEntity.getCreateUserId());
        msgNextObject.put("content", String.format(REFUND_PAY_PASS,
                moneyMainEntity.getReturnPayeeName(),
                moneyMainEntity.getCreateUserName(),
                moneyMainEntity.getPayUserName(),
                moneyMainEntity.getPayDate()));
        tokenDao.sendTextMsg(JSON.toJSONString(msgNextObject));

        //付款成功后给申请人发消息，保存消息到消息表t_sys_message
        messageEntity = new MessageEntity();
        messageEntity.setCreateUserId(moneyMainEntity.getCreateUserId());
        messageEntity.setCreateTime(messageDao.getCurrentTime());
        messageEntity.setContent(String.format(REFUND_PAY_PASS,
                moneyMainEntity.getReturnPayeeName(),
                moneyMainEntity.getCreateUserName(),
                moneyMainEntity.getPayUserName(),
                moneyMainEntity.getPayDate()));
        messageEntity.setMessageType(0);
        messageEntity.setMainId(id);
        messageEntity.setDelFlag(0);
        messageEntity.setOpenUrl("/page/apply/money/genzong_detail.html?id=" + moneyMainEntity.getId() + "&pageType=edit&openType=dialog");
        messageEntity.setOpenTitle(String.format(REFUND_PAY_PASS_MESSAGE, moneyMainEntity.getCreateUserName()));
        messageDao.add(messageEntity);

        //付款成功后给申请人发消息,保存消息到消息收件人表t_sys_message_receiver
        messageReceiverEntity = new MessageReceiverEntity();
        messageReceiverEntity.setMessageId(messageEntity.getId());
        messageReceiverEntity.setUserId(moneyMainEntity.getReturnPayeeId());
        messageReceiverEntity.setUserType(2);
        messageReceiverEntity.setReadFlag(0);
        messageReceiverDao.add(messageReceiverEntity);

        //发消息
        jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));*/

        result.put("message", jsonObjectList);
        result.put("flag", true);
        return result;
    }

    @Override
    public List<JSONObject> getPayerListByMoneyId(String moneyId) {
        return moneyPayerDao.getViewJSONListByCondition(" AND fkMoneyId = ? AND payerId IN(SELECT id FROM V_SYS_USER WHERE departName LIKE '%财务%' OR roleName LIKE '%财务%')", new String[]{moneyId});
        //return moneyPayerDao.getJSONListByCondition(" AND FK_MONEY_ID = ? ", new String[]{moneyId});
    }

    @Override
    public Boolean removeById(String id) {
        return moneyMainDao.removeById(id) > 0;
    }

    @Override
    public Boolean copierReturn(String id, String copierPersonId, String auditFlag, String copierReturnReason) {

        //保存历史审核信息
        AuditHistoryEntity auditHistoryEntity = new AuditHistoryEntity();
        auditHistoryEntity.setMainId(id);
        auditHistoryEntity.setAuditorId(copierPersonId);
        JSONObject user = userDao.getJSONById(copierPersonId);
        auditHistoryEntity.setAuditorName(user.getString("name"));
        auditHistoryEntity.setAuditFlag(auditFlag);
        auditHistoryEntity.setAuditAdvise(copierReturnReason);
        auditHistoryEntity.setAuditType(4);
        auditHistoryEntity.setAuditTime(moneyCopierDao.getCurrentTime());
        auditHistoryDao.add(auditHistoryEntity);

        boolean success = moneyMainDao.copierReturn(id, copierReturnReason) > 0;
        if (success) {
            //判断是否可以重新提交
            MoneyMainEntity mainEntity = moneyMainDao.getEntityById(id);
            if (copierReturnReason.contains("其他原因")) {
                mainEntity.setReturnType("1");
            } else {
                mainEntity.setReturnType("0");
            }
            moneyMainDao.update(mainEntity);
            //企业号 抄送人驳回
            JSONObject msgObject = new JSONObject();
            msgObject.put("userIds", mainEntity.getCreateUserId());
            msgObject.put("content", String.format(MONEY_COPIER_REJECT,
                    mainEntity.getCreateUserName(),
                    mainEntity.getType(),
                    mainEntity.getCopierReturnReason()));
            tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
        }
        return success;
    }

    @Override
    public Boolean payReturn(String id, String payReturnUserId, String payReturnUserName, String payReturnReasonType, String payReturnReasonDesc) {
        boolean success = moneyMainDao.payReturn(id, payReturnUserId, payReturnUserName, payReturnReasonType, payReturnReasonDesc) > 0;
        if (success) {
            //企业号: 付款审核驳回给申请人发消息
            MoneyMainEntity mainEntity = moneyMainDao.getEntityById(id);
            JSONObject msgObject = new JSONObject();
            msgObject.put("userIds", mainEntity.getCreateUserId());
            msgObject.put("content", String.format(MONEY_PAY_REJECT,
                    mainEntity.getCreateUserName(),
                    mainEntity.getType(),
                    mainEntity.getMoney(),
                    mainEntity.getPayReturnReasonDesc(),
                    mainEntity.getPayUserName(),
                    mainEntity.getPayDate()));
            tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
        }
        return success;
    }

    private JSONObject getMessage(MessageEntity messageEntity, MessageReceiverEntity messageReceiverEntity) {
        String userId = messageEntity.getCreateUserId();
        UserEntity userEntity = userDao.getById(userId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", messageEntity.getId());
        jsonObject.put("createUserId", userId);
        jsonObject.put("createUserName", userEntity.getName());
        jsonObject.put("createTime", messageEntity.getCreateTime());
        jsonObject.put("content", messageEntity.getContent());
        jsonObject.put("mainId", messageEntity.getMainId());
        jsonObject.put("delFlag", messageEntity.getDelFlag());
        jsonObject.put("openTitle", messageEntity.getOpenTitle());
        jsonObject.put("openUrl", messageEntity.getOpenUrl());
        jsonObject.put("messageType", messageEntity.getMessageType());
        jsonObject.put("receiverId", messageReceiverEntity.getId());
        jsonObject.put("receiverUserId", messageReceiverEntity.getUserId());
        jsonObject.put("receiverUserType", messageReceiverEntity.getUserType());
        jsonObject.put("receiverReadFlag", messageReceiverEntity.getReadFlag());
        return jsonObject;
    }

    //标记消息为已读 /0-审核人 /2-申请人 /1-抄送人(暂无)
    private void messageReceiverRead(String mainId, Integer userType) {
        StringBuffer sb = new StringBuffer();
        List<String> arg = new ArrayList<>();
        if (!StringUtils.isBlank(mainId)) {
            sb.append("AND mainId=?");
            arg.add(mainId);
        }
        if (null != userType) {
            sb.append("AND receiverUserType=?");
            arg.add(userType.toString());
        }
        String receiverIds = "";
        List<JSONObject> jsonObjectList = messageDao.getViewJSONListByCondition(sb.toString(), arg.toArray());
        if (null != jsonObjectList && jsonObjectList.size() > 0) {
            for (int i = 0; i < jsonObjectList.size(); i++) {
                receiverIds += "'" + jsonObjectList.get(i).getString("receiverId") + "',";
            }
        }
        if (receiverIds.length() > 1) {
            receiverIds = receiverIds.substring(0, receiverIds.length() - 1);
        } else {
            receiverIds = null;
        }
        if (!StringUtils.isBlank(receiverIds)) {
            messageReceiverDao.updateReadFlag("T_SYS_MESSAGE_RECEIVER", "AND ID IN (" + receiverIds + ")");
        }
    }

    /*@Override
    public JSONObject refundAudit(String jsonData) {
        JSONObject jsonObject = JSON.parseObject(jsonData);
        String id = jsonObject.getString("id");
        String userId = jsonObject.getString("userId");
        String refundFlag = jsonObject.getString("refundFlag");
        String advise = jsonObject.getString("advise");

        List<JSONObject> jsonObjectList = new ArrayList<>();
        //根据id获取主表信息
        MoneyMainEntity mainEntity = moneyMainDao.getEntityById(id);
        //保存历史审核信息
        AuditHistoryEntity auditHistoryEntity = new AuditHistoryEntity();
        auditHistoryEntity.setMainId(id);
        auditHistoryEntity.setAuditorId(userId);
        auditHistoryEntity.setAuditorName(mainEntity.getCurrentAuditorName());
        auditHistoryEntity.setAuditFlag(refundFlag);
        auditHistoryEntity.setAuditAdvise(advise);
        auditHistoryEntity.setAuditType(9);//回款占用9
        auditHistoryEntity.setAuditTime(auditDao.getCurrentTime());
        auditHistoryDao.add(auditHistoryEntity);

        //根据id获取审核信息
        List<AuditEntity> auditEntityList = (List<AuditEntity>) (Object) auditDao.getIBaseEntityByCondition(" AND MAIN_ID = ? ORDER BY AUDIT_SORT", new Object[]{id});

        for (int i = 0; i < auditEntityList.size(); i++) {
            AuditEntity auditEntity = auditEntityList.get(i);


            if (auditEntity.getAuditorId().equals(userId)) {
                mainEntity.setRefundFlag(refundFlag);

                auditEntity.setAuditAdvise(advise);
                auditEntity.setAuditFlag(Integer.parseInt(refundFlag));
                auditEntity.setAuditTime(auditDao.getCurrentTime());
            } else {
                mainEntity.setRefundFlag("0");
                if (auditEntity.getAuditFlag() == -1) {
                    auditEntity.setAuditFlag(0);
                    mainEntity.setCurrentAuditorName(auditEntity.getAuditorName());
                    mainEntity.setCurrentAuditorId(auditEntity.getAuditorId());

                    //企业号:给第一审核人发送消息
                    JSONObject msgObject = new JSONObject();
                    msgObject.put("userIds", auditEntity.getAuditorId());
                    msgObject.put("content", String.format(REFUND_AUDIT,
                            auditEntity.getAuditorName(),
                            mainEntity.getReturnPayeeName(),
                            mainEntity.getReturnPayeeName(),
                            DateUtils.parse(moneyMainDao.getCurrentTime(), "yyyy-MM-dd HH:mm")
                    ));
                    tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

                    messageReceiverRead(mainEntity.getId(), 0);
                    messageReceiverRead(mainEntity.getId(), 2);

                    //保存消息到消息表t_sys_message
                    MessageEntity messageEntity = new MessageEntity();
                    messageEntity.setCreateUserId(mainEntity.getReturnPayeeId());
                    messageEntity.setCreateTime(messageDao.getCurrentTime());
                    messageEntity.setContent(String.format(REFUND_AUDIT,
                            auditEntity.getAuditorName(),
                            mainEntity.getReturnPayeeName(),
                            mainEntity.getReturnPayeeName(),
                            DateUtils.parse(moneyMainDao.getCurrentTime(), "yyyy-MM-dd HH:mm")
                    ));
                    messageEntity.setMessageType(1);//1审核 0通知
                    messageEntity.setMainId(mainEntity.getId());
                    messageEntity.setDelFlag(0);
                    messageEntity.setOpenUrl("/page/apply/money/genzong_detail.html?id=" + mainEntity.getId() + "&pageType=applyAudit&openType=dialog");
                    messageEntity.setOpenTitle(String.format(REFUND_AUDIT_MESSAGE, mainEntity.getReturnPayeeName()));
                    messageDao.add(messageEntity);

                    //保存第一审核人信息到消息收件人表t_sys_message_receiver
                    MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
                    messageReceiverEntity.setMessageId(messageEntity.getId());
                    messageReceiverEntity.setUserId(mainEntity.getCurrentAuditorId());
                    messageReceiverEntity.setUserType(0);
                    messageReceiverEntity.setReadFlag(0);
                    messageReceiverDao.add(messageReceiverEntity);

                    //发消息
                    jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));

                }
            }
            moneyMainDao.update(mainEntity);
            auditDao.update(auditEntity);

            //驳回
            if (auditEntity.getAuditFlag() == 2) {

                //企业号:给第一审核人发送消息
                JSONObject msgObject = new JSONObject();
                msgObject.put("userIds", auditEntity.getAuditorId());
                msgObject.put("content", String.format(REFUND_AUDIT_REJECT,
                        mainEntity.getReturnPayeeName(),
                        auditEntity.getAuditorName(),
                        DateUtils.parse(moneyMainDao.getCurrentTime(), "yyyy-MM-dd HH:mm")
                ));
                tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

                messageReceiverRead(mainEntity.getId(), 0);
                messageReceiverRead(mainEntity.getId(), 2);

                //保存消息到消息表t_sys_message
                MessageEntity messageEntity = new MessageEntity();
                messageEntity.setCreateUserId(auditEntity.getAuditorId());
                messageEntity.setCreateTime(messageDao.getCurrentTime());
                messageEntity.setContent(String.format(REFUND_AUDIT_REJECT,
                        mainEntity.getReturnPayeeName(),
                        auditEntity.getAuditorName(),
                        DateUtils.parse(moneyMainDao.getCurrentTime(), "yyyy-MM-dd HH:mm")
                ));
                messageEntity.setMessageType(0);//1审核 0通知
                messageEntity.setMainId(mainEntity.getReturnPayeeId());
                messageEntity.setDelFlag(0);
                messageEntity.setOpenUrl("/page/apply/money/genzong_detail.html?id=" + mainEntity.getId() + "&pageType=edit&openType=dialog");
                messageEntity.setOpenTitle(String.format(REFUND_AUDIT_REJECT_MESSAGE, auditEntity.getAuditorName()));
                messageDao.add(messageEntity);

                //保存第一审核人信息到消息收件人表t_sys_message_receiver
                MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
                messageReceiverEntity.setMessageId(messageEntity.getId());
                messageReceiverEntity.setUserId(mainEntity.getReturnPayeeId());
                messageReceiverEntity.setUserType(2);
                messageReceiverEntity.setReadFlag(0);
                messageReceiverDao.add(messageReceiverEntity);

                //发消息
                jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));

                break;

            }
            //通过
            if (auditEntity.getAuditFlag() == 1 && i == auditEntityList.size() - 1) {
                //只有最后一个审核人会进来


                //企业号:给第一审核人发送消息
                JSONObject msgObject = new JSONObject();
                msgObject.put("userIds", auditEntity.getAuditorId());
                msgObject.put("content", String.format(REFUND_AUDIT_PASS,
                        mainEntity.getReturnPayeeName(),
                        auditEntity.getAuditorName(),
                        DateUtils.parse(moneyMainDao.getCurrentTime(), "yyyy-MM-dd HH:mm")
                ));
                tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

                messageReceiverRead(mainEntity.getId(), 0);
                messageReceiverRead(mainEntity.getId(), 2);

                //保存消息到消息表t_sys_message
                MessageEntity messageEntity = new MessageEntity();
                messageEntity.setCreateUserId(auditEntity.getAuditorId());
                messageEntity.setCreateTime(messageDao.getCurrentTime());
                messageEntity.setContent(String.format(REFUND_AUDIT_PASS,
                        mainEntity.getReturnPayeeName(),
                        auditEntity.getAuditorName(),
                        DateUtils.parse(moneyMainDao.getCurrentTime(), "yyyy-MM-dd HH:mm")
                ));
                messageEntity.setMessageType(0);//1审核 0通知
                messageEntity.setMainId(mainEntity.getReturnPayeeId());
                messageEntity.setDelFlag(0);
                messageEntity.setOpenUrl("/page/apply/money/genzong_detail.html?id=" + mainEntity.getId() + "&pageType=applyAudit&openType=dialog");
                messageEntity.setOpenTitle(String.format(REFUND_AUDIT_PASS_MESSAGE, auditEntity.getAuditorName()));
                messageDao.add(messageEntity);

                //保存第一审核人信息到消息收件人表t_sys_message_receiver
                MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
                messageReceiverEntity.setMessageId(messageEntity.getId());
                messageReceiverEntity.setUserId(mainEntity.getReturnPayeeId());
                messageReceiverEntity.setUserType(2);
                messageReceiverEntity.setReadFlag(0);
                messageReceiverDao.add(messageReceiverEntity);

                //发消息
                jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));


            }

        }

        JSONObject result = new JSONObject();
        result.put("flag", true);
        result.put("message", jsonObjectList);
        return result;
    }*/
    @Override
    public JSONObject refundAudit(String jsonData) {
        return null;
    }

    public List<AuditEntity> getRefundAudits(String userId, String mainId) {
        List<AuditEntity> auditEntityList = new ArrayList<>();
        String companyId = "";
        String parentId = "";
        String parentName = "";
        List<JSONObject> userList = userDao.getViewByUserId(" and id=?", new Object[]{userId});
        if (null != userList && userList.size() > 0) {
            JSONObject userJson = userList.get(0);
            companyId = userJson.getString("companyId");
            parentId = userJson.getString("parentId");
            parentName = userJson.getString("parentName");
        }
        if (!StringUtils.isBlank(parentId)) {
            AuditEntity auditEntity = new AuditEntity();
            JSONObject userJSON = userDao.getViewJSONById(parentId);
            auditEntity.setAuditFlag(-1);
            auditEntity.setMainId(mainId);
            auditEntity.setModuleName("moneyRefund");
            auditEntity.setRoleName(userJSON.getString("roleName"));
            auditEntity.setAuditorId(parentId);
            auditEntity.setAuditorName(parentName);
            auditEntity.setAuditSort(0);
            auditEntityList.add(auditEntity);
            auditDao.add(auditEntity);
        }
        if (!StringUtils.isBlank(companyId)) {
            //查找财务和服务，最后一个参数可以为null
            List<JSONObject> jsonObjectList = userDao.getUserByCompanyIdAndRoleName(userId, "财务会计", companyId, null);
            if (null != jsonObjectList && jsonObjectList.size() > 0) {
                JSONObject jsonObject = jsonObjectList.get(0);
                AuditEntity auditEntity = new AuditEntity();
                auditEntity.setAuditFlag(-1);
                auditEntity.setMainId(mainId);
                auditEntity.setModuleName("moneyRefund");
                auditEntity.setRoleName("财务会计");
                auditEntity.setAuditorId(jsonObject.getString("userId"));
                auditEntity.setAuditorName(jsonObject.getString("userName"));
                auditEntity.setAuditSort(1);
                auditEntityList.add(auditEntity);
                auditDao.add(auditEntity);
            }
        }
        return auditEntityList;
    }


    /**
     * 模糊查询收款人银卡卡号和开户行
     *
     * @param userId
     * @param payeeName
     * @return
     */
    @Override
    public List<JSONObject> getPayeeList(String userId, String payeeName) {
        return moneyPayeeDao.getPayeeList(userId, payeeName);
    }
}
